package cn.hxsteel.storage.module.tempturnover;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hxsteel.jtool.util.TimeUtil;
import cn.hxsteel.storage.core.config.Config;
import cn.hxsteel.storage.core.config.constant.SheetConst.StepKindEnum;
import cn.hxsteel.storage.core.tool.SheetTool;
import cn.hxsteel.storage.model.dao.GoodsDAO;
import cn.hxsteel.storage.model.dao.SheetDAO;
import cn.hxsteel.storage.model.dao.SheetDetailDAO;
import cn.hxsteel.storage.model.po.GoodsPO;
import cn.hxsteel.storage.model.po.SheetDetailPO;
import cn.hxsteel.storage.model.po.SheetPO;
import cn.hxsteel.storage.module.tempturnover.model.SheetDetailWSO;
import cn.hxsteel.storage.module.tempturnover.model.SheetWSO;
import cn.hxsteel.storage.module.tempturnover.model.SyncVO;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;

/**
 * 数据同步服务
 */
@Service
public class SyncService
{
    @Autowired
    private SheetDAO       sheetDAO;
    @Autowired
    private SheetDetailDAO sheetDetailDAO;
    @Autowired
    private GoodsDAO       goodsDAO;
    
    private int            syncRecord;
    private WebService     webService;
    private String         winLastRecordCode = "";
    private String         outLastRecordCode = "";
    
    /**
     * 初始化，在storage-service.xml中配置，被自动调用
     */
    @PostConstruct
    public void init()
    {
	webService = new WebService();
    }
    
    /**
     * 获取同步信息，包括同步时间和同步条数
     */
    public SyncVO giveSyncInfo()
    {
	SyncVO syncVO = new SyncVO();
	syncVO.setSyncTime( TimeUtil.getTime() );
	syncVO.setSyncRecord( syncRecord );
	syncVO.setSuccess( webService.isSuccess() );
	return syncVO;
    }
    
    /**
     * 同步商品目录
     */
    public void syncGoodsList()
    {
	List< SheetDetailWSO > sheetDetails = webService.giveSheetDetailListByCount( goodsDAO.selCount() );
	
	if ( sheetDetails != null )
	{
	    for ( SheetDetailWSO sheetDetailWSO : sheetDetails )
	    {
		GoodsPO goodsPO = giveGoodsPO( sheetDetailWSO );
		goodsDAO.save( goodsPO );
	    }
	}
    }
    
    /** 查询商品对象 */
    private GoodsPO giveGoodsPO( SheetDetailWSO sheetDetailWSO )
    {
	GoodsPO goodsPO = new GoodsPO();
	goodsPO.setName( sheetDetailWSO.getName() );
	goodsPO.setMaterial( sheetDetailWSO.getMaterial() );
	goodsPO.setOrigin( sheetDetailWSO.getOrigin() );
	goodsPO.setNorm( sheetDetailWSO.getNorm() );
	return goodsPO;
    }
    
    /**
     * 同步出库单据和出库明细
     */
    public void syncSheet()
    {
	// 重置同步记录数
	syncRecord = 0;
	List< SheetWSO > sheets = giveSheetList();
	
	if ( sheets != null )
	{
	    syncRecord = sheets.size();
	    
	    for ( SheetWSO sheetWSO : sheets )
	    {
		SheetPO sheetPO = addSheet( sheetWSO );
		addDetail( sheetWSO.getKey(), sheetPO );
	    }
	}
    }
    
    /** 通过最新一条记录的创建时间获取webService端的最新出库单记录 */
    private List< SheetWSO > giveSheetList()
    {
	SheetPO lastestSheet = null;
	SheetPO winSheetPO = sheetDAO.selLatestSheet( 0 );
	SheetPO outSheetPO = sheetDAO.selLatestSheet( 1 );
	
	if ( winSheetPO != null && outSheetPO != null )
	{
	    lastestSheet = winSheetPO.getId() < outSheetPO.getId() ? outSheetPO : winSheetPO;
	    winLastRecordCode = winSheetPO.getCode();
	    outLastRecordCode = outSheetPO.getCode();
	}
	else if ( winSheetPO != null )
	{
	    lastestSheet = winSheetPO;
	    winLastRecordCode = winSheetPO.getCode();
	}
	else if ( outSheetPO != null )
	{
	    lastestSheet = outSheetPO;
	    outLastRecordCode = outSheetPO.getCode();
	}
	else
	{
	    return webService.giveSheetList( TimeUtil.getTime( TimeUtil.DATE ) );
	}
	
	String createTime = lastestSheet == null ? TimeUtil.getTime( TimeUtil.DATE ) : lastestSheet.getCreateTime().toString();
	return webService.giveSheetList( createTime );
    }
    
    /** 添加单据 */
    private SheetPO addSheet( SheetWSO sheetWSO )
    {
	SheetPO sheetPO = new SheetPO();
	sheetPO.setCreateTime( sheetWSO.getCreateTime() );
	String lastRecordCode = createCode( sheetWSO.getKey() );
	if ( lastRecordCode.startsWith( SheetTool.OUT ) )
	{
	    sheetPO.setKind( true );
	}
	sheetPO.setCode( lastRecordCode );
	sheetPO.setStepKind( (byte) StepKindEnum.RESERVE.ordinal() );
	sheetDAO.save( sheetPO );
	
	return sheetPO;
    }
    
    /** 根据高达出库单编号中的日期信息生成新出库单编号 */
    private String createCode( String key )
    {
	String gdDate = "";
	
	// 进SH、出STCK
	if ( key.startsWith( "SH" ) )
	{
	    gdDate = key.substring( 2, 8 );
	    winLastRecordCode = SheetTool.createWinCode( gdDate, winLastRecordCode );
	    return winLastRecordCode;
	}
	else
	{
	    gdDate = key.substring( 4, 10 );
	    outLastRecordCode = SheetTool.createOutCode( gdDate, outLastRecordCode );
	    return outLastRecordCode;
	}
    }
    
    /** 更新库存明细 */
    private void addDetail( String key, SheetPO sheetPO )
    {
	List< SheetDetailWSO > details = webService.giveSheetDetailByKey( key );
	
	if ( details.size() > 0 )
	{
	    for ( SheetDetailWSO sheetDetailVO : details )
	    {
		SheetDetailPO sheetDetailPO = new SheetDetailPO();
		// sheetDetailPO.setSheetID( sheetPO.getId() );
		sheetDetailPO.setGoodsID( giveGoodsID( sheetDetailVO ) );
		// 如果是出库单需要将数量和重量改为等值负数
		if ( sheetPO.getCode().substring( 0, 3 ).equals( SheetTool.WIN ) )
		{
		    sheetDetailPO.setNumber( sheetDetailVO.getNumber() );
		    sheetDetailPO.setWeight( sheetDetailVO.getWeight() );
		}
		else
		{
		    sheetDetailPO.setNumber( (short) -sheetDetailVO.getNumber() );
		    sheetDetailPO.setWeight( -sheetDetailVO.getWeight() );
		}
		sheetDetailDAO.save( sheetDetailPO );
	    }
	}
    }
    
    /** 查询对应商品的ID */
    private int giveGoodsID( SheetDetailWSO sheetDetailWSO )
    {
	System.err.println( sheetDetailWSO.getKey() );
	// @formatter:off
	GoodsPO goodsPO = goodsDAO.selObj( 
		sheetDetailWSO.getName(), 
		sheetDetailWSO.getMaterial(),
		sheetDetailWSO.getOrigin(), 
		sheetDetailWSO.getNorm() );
	return goodsPO.getId();
    }
}

/**
 * 用于获取高达软件数据的webservice
 */
//[start]
class WebService
{
    private boolean isSuccess = false;
    private Client client = Client.create();
    
    /**
     * 按给定日期查询最新的出库单据列表，如果给定日期为空字符串则返回所有的历史单据列表
     * 
     * @param dateTime 日期的字符串形式（格式：2012-12-14 14:12:45:265）
     */
    public List< SheetWSO > giveSheetList( String dateTime )
    {
	dateTime = dateTime.replace( " ", "%20" );
	List< SheetWSO > res = null;
	try
        {
	    res = getWebResource( "/sheet/selListByDateTime?dateTime=" + dateTime ).get( new GenericType< List< SheetWSO >>() {} );
	    isSuccess = true;
	    if ( res.size() == 0 )
	    {
		res = null;
	    }
        }
	catch ( ClientHandlerException e )
        {
	    isSuccess = false;
	    System.err.println( "连接失败！" );
        }
	
	return res;
    }

    /**
     * 按出库单号返回该单号的出库明细列表
     * 
     * @param key 关键字（格式如：STCK1212140064）
     */
    public List< SheetDetailWSO > giveSheetDetailByKey( String key )
    {
	List< SheetDetailWSO > res = null;
	try
        {
	    res = getWebResource( "/sheetDetail/selListByKey?key=" + key ).get( new GenericType< List< SheetDetailWSO >>() {} );
	    isSuccess = true;
	    if ( res.size() == 0 )
	    {
		res = null;
	    }
        }
        catch ( ClientHandlerException e )
        {
            isSuccess = false;
            System.err.println( "连接失败！" );
        }
	
	return res;
    }
    
    /**
     * 根据本地商品目录总数返回远程新的未同步的商品目录列表，返回的商品包含在库存明细对象中，需重新分解
     * 
     * @param count 本地商品目录总数
     */
    public List< SheetDetailWSO > giveSheetDetailListByCount( int count )
    {
	List< SheetDetailWSO > res = null;
	try
        {
	    res = getWebResource( "/sheetDetail/selGoodsListByCount?count=" + count ).get( new GenericType< List< SheetDetailWSO >>() {} );
	    isSuccess = true;
	    if ( res.size() == 0 )
	    {
		res = null;
	    }
        }
        catch ( ClientHandlerException e )
        {
            isSuccess = false;
	    System.err.println( "连接失败！" );
        }
	
	return res;
    }
    
    /**
     * 获取web service 访问接口
     * 
     * @param url 链接地址
     */
    private WebResource getWebResource( String url )
    {
	return client.resource( Config.tempturnoverWebserviceDomain + url );
    }

    public boolean isSuccess()
    {
	return isSuccess;
    }

    public void setSuccess( boolean isSuccess )
    {
	this.isSuccess = isSuccess;
    }
}
//[end]